//
//  AgentDetailViewController.m
//  BaseProject
//
//  Created by 王洋 on 2021/3/2.
//  Copyright © 2021 王洋. All rights reserved.
//

#import "JXPagerView.h"
//#import <JXCategoryView/JXCategoryBaseView.h>
#import <JXCategoryView/JXCategoryView.h>
#import "AgentDetailHeaderView.h"
#import "AgentDetailListView.h"
#import "AgentInfoViewController.h"
#import "UserOrderListViewController.h"
#import "AgentDetailViewController.h"
#import "InviteFriendsVc.h"
#import "CommonRecommandUserModel.h"
static const CGFloat JXTableHeaderViewHeight = 200;
static const CGFloat JXheightForHeaderInSection = 44;

@interface AgentDetailViewController () <JXPagerViewDelegate, JXCategoryViewDelegate>

@property (nonatomic, strong) JXPagerView *pagingView;
@property (nonatomic, strong) AgentDetailHeaderView *headerView;
@property (nonatomic, strong) JXCategoryTitleView *categoryView;
@property (nonatomic, strong) NSArray <NSString *> *titles;

@property (nonatomic, strong) AgentDetailListView *recList;
@property (nonatomic, strong) NSMutableArray <CommonRecommandUserModel *>*recDataArray;

@property (nonatomic, strong) AgentDetailListView *subsidyList;
@property (nonatomic, strong) NSMutableArray <CommonRecommandUserModel *>*subDataArray;

@property (nonatomic, assign) NSInteger recPageNum;
//@property (nonatomic, assign) NSInteger subPageNum;
@property (nonatomic, assign) NSInteger pageSize;

@end

@implementation AgentDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareData];
    [self initView];
    [self requestData];

}

- (void)requestData {
    [self refreshParam];
    [self request_recList];
    [self request_recOrderList];
}

- (void)refreshParam {
    self.recPageNum = 1;
//    self.subPageNum = 1;
    self.pageSize = 20;
}

- (void)prepareData {
    _titles = @[@"我推荐的用户", @"补贴明细"];
}

- (void)initView {
    
    self.title = @"推荐官收益";
    [self.view addSubview:self.pagingView];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitleColor:UIColorHex(0x333333) forState:UIControlStateNormal];
    [rightBtn setTitle:@"我的资料" forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(goInfo) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    rightBtn.frame = CGRectMake(0,0,66,30);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

    self.navigationItem.rightBarButtonItems =@[rightItem];
    
    [self initViewAction];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    self.pagingView.frame = self.view.bounds;
}

- (void)initViewAction {
    
    WEAKSELF
    self.headerView.AgentDetailHeaderViewBlock = ^{
        InviteFriendsVc *vc = [[InviteFriendsVc alloc] init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    self.recList.tableView.mj_footer =  [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.recPageNum ++;
            [weakSelf request_recList];
        });
    }];
    
    self.recList.didSelectRowAtIndexPath = ^(NSIndexPath * _Nonnull indexPath) {
        
    };
}

- (void)goInfo {
    AgentInfoViewController *vc = [[AgentInfoViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - JXPagingViewDelegate

- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    return self.headerView;
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    return JXTableHeaderViewHeight;
}

- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return JXheightForHeaderInSection;
}

- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return self.categoryView;
}

- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    return self.titles.count;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    if (index == 0) {
        return self.recList;
    } else {
        return self.subsidyList;
    }
}

- (void)mainTableViewDidScroll:(UIScrollView *)scrollView {
    [self.headerView scrollViewDidScroll:scrollView.contentOffset.y];
}

#pragma mark - JXCategoryViewDelegate

- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
}

- (JXCategoryTitleView *)categoryView {
    if (!_categoryView) {
        _categoryView = [[JXCategoryTitleView alloc] init];
        _categoryView.bounds = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, JXheightForHeaderInSection);
        _categoryView.titles = self.titles;
        _categoryView.backgroundColor = [UIColor whiteColor];
        _categoryView.delegate = self;
        _categoryView.titleSelectedColor = UIColorHex(0x222222);
        _categoryView.titleSelectedFont = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
        _categoryView.titleColor = UIColorHex(0x333333);
        _categoryView.titleFont = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
        _categoryView.titleColorGradientEnabled = YES;

        JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
        lineView.indicatorColor = UIColorHex(0xff4242);
        lineView.indicatorWidth = 20;
        
        _categoryView.indicators = @[lineView];
        _categoryView.listContainer = (id<JXCategoryViewListContainer>)self.pagingView.listContainerView;
    }
    return _categoryView;
}

- (JXPagerView *)pagingView {
    if (!_pagingView) {
        _pagingView = [[JXPagerView alloc] initWithDelegate:self];
    }
    return _pagingView;
}

- (AgentDetailHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[NSBundle mainBundle] loadNibNamed:@"AgentDetailHeaderView"
                                                    owner:nil
                                                  options:nil].firstObject;
    }
    return _headerView;
}

- (AgentDetailListView *)recList {
    if (!_recList) {
        _recList = [[AgentDetailListView alloc] initWithType:AgentDetailSegType_recUsers];
    }
    return _recList;
}

- (AgentDetailListView *)subsidyList {
    if (!_subsidyList) {
        _subsidyList = [[AgentDetailListView alloc] initWithType:AgentDetailSegType_subsidies];
    }
    return _subsidyList;
}

- (NSMutableArray<CommonRecommandUserModel *> *)subDataArray {
    if (!_subDataArray) {
        _subDataArray = @[].mutableCopy;
    }
    return _subDataArray;
}

- (NSMutableArray<CommonRecommandUserModel *> *)recDataArray {
    if (!_recDataArray) {
        _recDataArray = @[].mutableCopy;
    }
    return _recDataArray;
}

- (void)request_recList {
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSMutableDictionary *t = @{}.mutableCopy;
    [t setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    [dic setValue:t forKey:@"t"];
    [dic setValue:@(self.recPageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_GetRecList];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.recList.tableView.mj_header endRefreshing];
        [weakSelf.recList.tableView.mj_footer endRefreshing];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                NSArray *list = [resultDic valueForKey:@"list"];
                if ([list isKindOfClass:[NSArray class]]) {
                    
                    if (weakSelf.recPageNum == 1) {
                        weakSelf.recDataArray = @[].mutableCopy;
                    }
                    
                    for (int i = 0; i < list.count; i++) {
                        NSDictionary *listDic = list[i];
                        CommonRecommandUserModel *model = [CommonRecommandUserModel modelWithDictionary:listDic];
                        [weakSelf.recDataArray addObject:model];
                    }
                }
                weakSelf.recList.dataSource = weakSelf.recDataArray.mutableCopy;
                [weakSelf.recList.tableView reloadData];
                
            } else {
               [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
               [SVProgressHUD dismissWithDelay:1];
           }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [weakSelf.recList.tableView.mj_header endRefreshing];
        [weakSelf.recList.tableView.mj_footer endRefreshing];
    }];
}

- (void)request_recOrderList {
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_RecOrder];
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"userId"];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        [weakSelf.subsidyList.tableView.mj_header endRefreshing];
        [weakSelf.subsidyList.tableView.mj_footer endRefreshing];
        if ([data isKindOfClass:[NSDictionary class]]) {
            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if (![resultDic isKindOfClass:[NSDictionary class]]) {
                    return;
                }
                UserBalanceInfoModel *headModel = [UserBalanceInfoModel modelWithDictionary:resultDic];
                [weakSelf.headerView fillWithModel:headModel];
                {
                    NSArray *list = [resultDic valueForKey:@"yunOrderList"];
                    if ([list isKindOfClass:[NSArray class]]) {
                        weakSelf.subDataArray = @[].mutableCopy;
                        for (int i = 0; i < list.count; i++) {
                            NSDictionary *listDic = list[i];
                            if ([listDic isKindOfClass:[NSDictionary class]]) {
                                CommonRecommandUserModel *model = [CommonRecommandUserModel modelWithDictionary:listDic];
                                model.isBuTieMingXi = YES;
                                [weakSelf.subDataArray addObject:model];
                            }
                        }
                        weakSelf.subsidyList.dataSource = weakSelf.subDataArray.mutableCopy;
                        [weakSelf.subsidyList.tableView reloadData];
                    }
                }
                {
                    NSArray *list = [resultDic valueForKey:@"userRecommendListVo"];
                    if ([list isKindOfClass:[NSArray class]]) {
                        weakSelf.subDataArray = @[].mutableCopy;
                        for (int i = 0; i < list.count; i++) {
                            NSDictionary *listDic = list[i];
                            if ([listDic isKindOfClass:[NSDictionary class]]) {
                                CommonRecommandUserModel *model = [CommonRecommandUserModel modelWithDictionary:listDic];
                                model.isBuTieMingXi = YES;
                                [weakSelf.subDataArray addObject:model];
                            }
                        }
                        weakSelf.subsidyList.dataSource = weakSelf.subDataArray.mutableCopy;
                        [weakSelf.subsidyList.tableView reloadData];
                    }
                }
            }
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        [weakSelf.subsidyList.tableView.mj_header endRefreshing];
        [weakSelf.subsidyList.tableView.mj_footer endRefreshing];
    }];
}

@end
